<template>
  <div>
    <div class="searchDiv">
      <el-input placeholder="请输入商品名称关键字" v-model="query" clearable>
        <el-button slot="append" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-input>
    </div>
    <div>
      <el-table
        ref="multiTable"
        @select="select"
        @select-all="selectAll"
        :data="cartData.cartProductVoList"
        stripe
      >
        <el-table-column type="selection" aria-checked></el-table-column>
        <el-table-column min-width="200px" prop="productName" label="商品名称"></el-table-column>
        <el-table-column min-width="120px" label="数量">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.quantity"
              @change="quantity($event,scope.row.productId)"
              :min="1"
              :max="scope.row.productStock"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column min-width="100px" prop="productPrice" label="单价(元)"></el-table-column>
        <el-table-column min-width="100px" prop="productTotalPrice" label="合计(元)"></el-table-column>
        <el-table-column min-width="100px" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="deleteProduct(scope.row.productId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-card class="endCard">
        <el-row class="row">
          <el-col :span="4">
            <span>
              总计：
              <small style="color:red;">
                ￥
                <strong>{{cartData.cartTotalPrice}}</strong>
              </small>
            </span>
          </el-col>
          <el-col :span="16">
            <el-button type="primary" @click="submitOrder">提交订单</el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="warning" @click="clearCart">清空购物车</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      query: '',
      cartData: {}
    }
  },
  created() {
    this.getCartList()
  },
  methods: {
    search() {
      const routeData = this.$router.resolve({
        path: '/productList',
        query: {
          query: this.query
        }
      })
      window.open(routeData.href, '_blank')
    },
    async getCartList() {
      const { data: res } = await this.$axios.get('manage/cart/list')
      if (res.status !== 0) return this.$message.error(res.msg)
      this.cartData = res.data
      // 渲染默认选中/未选中
      this.checkOrUncheck()
    },
    async quantity(value, id) {
      const info = new FormData()
      info.append('id', id)
      info.append('count', value)
      const { data: res } = await this.$axios.put('manage/cart/update_count', info)
      if (res.status !== 0) return this.$message.error(res.msg)
      this.cartData = res.data
      this.checkOrUncheck()
    },
    async select(selection, row) {
      let url = ''
      if (row.productChecked === 1) {
        url = 'manage/cart/un_select/' + row.productId
      } else {
        url = 'manage/cart/select/' + row.productId
      }
      const { data: res } = await this.$axios.put(url)
      if (res.status !== 0) return this.$message.error(res.msg)
      this.cartData = res.data
      this.checkOrUncheck()
    },
    async selectAll(selection) {
      let url = ''
      if (selection.length === 0) {
        url = 'manage/cart/un_select_all'
      } else {
        url = 'manage/cart/select_all'
      }
      const { data: res } = await this.$axios.post(url)
      if (res.status !== 0) return this.$message.error(res.msg)
      this.cartData = res.data
      this.checkOrUncheck()
    },
    checkOrUncheck() {
      this.$nextTick(() => {
        this.cartData.cartProductVoList.forEach((value, index) => {
          this.$refs.multiTable.toggleRowSelection(value, value.productChecked === 1)
        })
      })
    },
    deleteProduct(id) {
      this.$confirm('此操作会永久删除该条数据，是否继续？', '删除提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const info = new FormData()
          info.append('IDs', id)
          const { data: res } = await this.$axios.post('manage/cart/delete', info)
          if (res.status !== 0) return this.$message.error(res.msg)
          this.cartData = res.data
          this.checkOrUncheck()
        })
        .catch(() => {
          this.$message.error('删除操作有误！')
        })
    },
    submitOrder() {
      if (this.cartData.cartProductVoList.length !== 0) {
        this.$confirm('此操作将提交选中的购物车内容，生成订单，是否继续？', '提交订单', {
          confirmButtonText: '提交',
          cancelButtonText: '取消',
          type: 'success'
        })
          .then(() => {
            let flag = false
            this.cartData.cartProductVoList.some(value => {
              if (value.productChecked === 1) {
                flag = true
                return true
              }
              flag = false
            })
            if (!flag) return this.$message.error('未选中任何商品')
            this.$router.push('/checkOrder')
          })
          .catch(() => {})
      } else {
        this.$message.warning('购物车没有内容')
      }
    },
    clearCart() {
      if (this.cartData.cartProductVoList.length !== 0) {
        this.$confirm('此操作将清空购物车所有内容，是否继续？', '清空购物车', {
          confirmButtonText: '清空',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const IDs = []
            this.cartData.cartProductVoList.forEach(value => {
              IDs.push(value.productId)
            })
            const info = new FormData()
            info.append('IDs', IDs)
            const { data: res } = await this.$axios.post('manage/cart/delete', info)
            if (res.status !== 0) return this.$message.error(res.msg)
            this.cartData = res.data
            this.checkOrUncheck()
          })
          .catch(() => {
            this.$message.error('删除操作有误！')
          })
      } else {
        this.$message.warning('购物车没有内容')
      }
    }
  }
}
</script>

<style lang="less">
.el-table td,
.el-table th {
  text-align: center;
}
</style>
<style lang="less" scoped>
.searchDiv {
  display: flex;
  justify-content: center;
  .el-input {
    width: 500px;
  }
}

.endCard {
  margin-top: 10px;
  .row {
    text-align: center;
    display: flex;
    align-items: center;
  }
}
</style>
